//
//  GetDataFromURLTool.m
//  WeatherGuide
//
//  Created by lanou3g on 15/12/17.
//  Copyright © 2015年 李明. All rights reserved.
//

#import "GetDataFromURLTool.h"
#import <UIKit/UIKit.h>

#import "Suggestion.h"
#import "Aqi.h"
#import "Weather.h"
#import "DailyForecast.h"
#import "AppDelegate.h"
#import "HourlyForecast.h"

@interface GetDataFromURLTool ()



@end


@implementation GetDataFromURLTool

//获取网络数据
+ (void)getDataFromURLStr:(NSString *)urlStr
                backBlock:(BackBlock)backBlock
{

    urlStr = [NSString stringWithFormat:@"https://api.heweather.com/x3/weather?city=%@&key=3bb198033c6f47beada29e0874636479",urlStr];
    
    
    CGFloat floatValue = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (floatValue >= 9.0f) {
        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlStr]];
    }else if (5.0f <=floatValue && floatValue < 9.0f ){
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    
 
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
  
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        @autoreleasepool {
            if (nil == error) {
                NSError *error1;
                NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error1];
                Weather *weather = [GetDataFromURLTool getModelForObject:object];
                ;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    backBlock(weather);
          
                });
            }else{
                NSLog(@"GetDataFromURLTool%@",error);
            }
        }
    }];
    [dataTask resume];

}

+ (Weather *)getModelForObject:(NSDictionary *)object
{

    NSLog(@"getModelForObject");
    NSArray *dataService = object[@"HeWeather data service 3.0"];
    NSDictionary *dicWeather = dataService.firstObject;
    NSDictionary *dicCity = dicWeather[@"aqi"];
    NSDictionary *dicAqi = dicCity[@"city"];
    NSArray *arrKey = [dicAqi allKeys];
    NSMutableDictionary *mutableDicAqi = [NSMutableDictionary dictionary];
    
    for (NSString *str in arrKey) {
        if ([str isEqualToString:@"qlty"]) {
            [mutableDicAqi setObject:[dicAqi valueForKey:str] forKey:str];
        }else{
            [mutableDicAqi setObject:[NSString stringWithFormat:@"%@",[dicAqi valueForKey:str]] forKey:str];
        }
    }
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    Aqi *aqi = [NSEntityDescription insertNewObjectForEntityForName:@"Aqi" inManagedObjectContext:app.managedObjectContext];

    [aqi setValuesForKeysWithDictionary:mutableDicAqi];

    NSArray *arrayDailyForecast = dicWeather[@"daily_forecast"];
    NSDictionary *dictSuggestion = dicWeather[@"suggestion"];
    NSArray *arrayHourlyForecast = dicWeather[@"hourly_forecast"];
    NSDictionary *dicNow = dicWeather[@"now"];
    NSDictionary *dicBasic = dicWeather[@"basic"];
    NSString *strCity = dicBasic[@"city"];

    NSMutableDictionary *dicDailyForecast = [GetDataFromURLTool getDailForecastDataForArray:arrayDailyForecast app:app];
    NSMutableDictionary *dicSuggestion = [GetDataFromURLTool getSuggestionDataForDic:dictSuggestion app:app];
    NSMutableDictionary *dicHourlyForecast = [GetDataFromURLTool getHourlyForecastDataForArray:arrayHourlyForecast withNowDic:dicNow app:app];
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Weather"];
 
    if (strCity.length == 0) {
        return nil;
    }
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city CONTAINS %@",strCity];

    request.predicate = predicate;
    
    

    NSError *error;

    NSArray *array = [app.managedObjectContext executeFetchRequest:request error:&error];
    Weather *weather;
    

    
    if (array.count == 0) {
         weather = [NSEntityDescription insertNewObjectForEntityForName:@"Weather" inManagedObjectContext:app.managedObjectContext];
    }else{
        weather = array.firstObject;
    }
    NSDictionary *dicWond = dicNow[@"cond"];
    [weather setValuesForKeysWithDictionary:dicWond];
    [weather setValuesForKeysWithDictionary:dicNow];
    [weather setValue:strCity forKey:@"city"];
    [weather setValue:aqi forKey:@"aqi"];
    [weather setValuesForKeysWithDictionary:dicDailyForecast];
    [weather setValuesForKeysWithDictionary:dicSuggestion];
    [weather setValuesForKeysWithDictionary:dicHourlyForecast];
    
    NSArray *arrayCity = [[NSUserDefaults standardUserDefaults] arrayForKey:@"city"];
    NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:arrayCity];
    NSLog(@" mutableArray = %@",arrayCity);
    if (arrayCity.count == 0) {
        NSLog(@"1111111111");
        [mutableArray addObject:weather.city];
        [[NSUserDefaults standardUserDefaults] setObject:mutableArray forKey:@"city"];
    }else{
        NSLog(@"哈哈哈哈哈哈");
        
        if (![arrayCity containsObject:weather.city]) {
            [mutableArray addObject:weather.city];
            NSLog(@" mutableArray = %@",mutableArray);
            [[NSUserDefaults standardUserDefaults] setObject:mutableArray forKey:@"city"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
    [app saveContext];
    return weather;
    
}

#pragma mark - DailForecast赋值
+ (NSMutableDictionary *)getDailForecastDataForArray:(NSArray *)array app:(AppDelegate *)app
{

    NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
    NSInteger i = 1;
    for (NSMutableDictionary *dic in array) {
        DailyForecast *dailyForecast = [NSEntityDescription insertNewObjectForEntityForName:@"DailyForecast" inManagedObjectContext:app.managedObjectContext];
        NSDictionary *dicCond = dic[@"cond"];
//        NSLog(@"dicCond = %@",dicCond);
        [dic removeObjectForKey:@"cond"];
        NSString *txt_d = [dicCond valueForKey:@"txt_d"];
        NSString *txt_n = [dicCond valueForKey:@"txt_n"];
        if ([txt_n isEqualToString:txt_d]) {
            dailyForecast.cond = txt_d;
        }else{
             dailyForecast.cond = [NSString stringWithFormat:@"%@转%@",txt_d,txt_n];
        }
//        dailyForecast.cond_n = [NSString stringWithFormat:@"%@",[dicCond valueForKey:@"code_n"]];
        [dailyForecast setValuesForKeysWithDictionary:dicCond];
        [dailyForecast setValuesForKeysWithDictionary:dic];
        NSDictionary *dicTmp = dic[@"tmp"];
        [dailyForecast setValuesForKeysWithDictionary:dicTmp];
        NSDictionary *dicWind = dic[@"wind"];
        [dailyForecast setValuesForKeysWithDictionary:dicWind];
        [mutableDic setObject:dailyForecast forKey:[NSString stringWithFormat:@"dailyForecast%ld",i]];
        i++;
    }
    return mutableDic;
}

#pragma mark - Suggestion赋值
+ (NSMutableDictionary *)getSuggestionDataForDic:(NSDictionary *)dic app:(AppDelegate *)app
{
    NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
    NSArray *arrayKey = [dic allKeys];

    for (NSString *str in arrayKey) {
        Suggestion *suggestion = [NSEntityDescription insertNewObjectForEntityForName:@"Suggestion" inManagedObjectContext:app.managedObjectContext];
        NSDictionary *dict = [dic valueForKey:str];
        [suggestion setValuesForKeysWithDictionary:dict];

        [mutableDic setObject:suggestion forKey:str];
    }
    return mutableDic;
}

#pragma mark - hourlyForecast赋值
+ (NSMutableDictionary *)getHourlyForecastDataForArray:(NSArray *)array withNowDic:(NSDictionary *)dic app:(AppDelegate *)app
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    NSInteger i = 1;
    for (NSDictionary *dic in array) {
        HourlyForecast *hourlyForecast = [NSEntityDescription insertNewObjectForEntityForName:@"HourlyForecast" inManagedObjectContext:app.managedObjectContext];
        [hourlyForecast setValuesForKeysWithDictionary:dic];
        NSDictionary *dicWind = dic[@"wind"];
        [hourlyForecast setValuesForKeysWithDictionary:dicWind];
        
        [dict setObject:hourlyForecast forKey:[NSString stringWithFormat:@"hourlyForecast%ld",i]];
        i++;
        
    }

    return dict;
}


@end
